import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import "element-ui/lib/theme-chalk/index.css"
import store from './store'

import { getRequest, postRequest, putRequest, deleteRequest } from '@/utils/api'
import { downloadRequest } from './utils/download'
import { initMenus } from './utils/menus'

Vue.config.productionTip = false

//修复新版本ElementUI el-date-picker报错问题
function RepairProps(cmp) {
  (cmp.mixins || []).forEach(mixin => {
    if (mixin.props && mixin.props.placement) {
      const defaultValue = mixin.props.placement.default
      mixin.data = new Proxy(mixin.data, {
        apply(target, thisArg, argArray) {
          const res = Reflect.apply(target, thisArg, argArray)
          return {
            ...(res || {}),
            placement: defaultValue
          }
        }
      })
      delete mixin.props.placement
    }
    if (mixin.mixins && mixin.mixins.length > 0) {
      RepairProps(mixin)
    }
  })
}

RepairProps(ElementUI.DatePicker)
RepairProps(ElementUI.TimePicker)
RepairProps(ElementUI.TimeSelect)

Vue.use(ElementUI, { size: "small" })


Vue.prototype.getRequest = getRequest
Vue.prototype.postRequest = postRequest
Vue.prototype.putRequest = putRequest
Vue.prototype.deleteRequest = deleteRequest
Vue.prototype.downloadRequest = downloadRequest

router.beforeEach((to, from, next) => {

  //不是登录,做处理
  if (to.path !== '/') {
    //判断有无登录，
    if (window.sessionStorage.getItem('tokenStr')) {

      if (!store.state.stomp) {
        //建立WebSocket
        store.dispatch('connect');
      }

      //初始化动态路由
      initMenus(router, store)

      //保存登录用户信息
      if (!window.sessionStorage.getItem('admin')) {
        return getRequest('/admin/info').then(resp => {
          if (resp) {
            window.sessionStorage.setItem('admin', JSON.stringify(resp));
            store.commit('initCurrentAdmin', resp)
          }
          next({ path: to.path })
        })
      }
      next();
    } else {
      next('/?redirect=' + to.path)
    }

  } else {
    //是登录,直接放行
    next()
  }

})






new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
